/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Table, TableBody, TableRow, CCell, TableHead, Text,
    useTheme, Button,
} from "customize-easy-ui-component";
import {DirectLink, Link as RouterLink,} from "../../../routing/Link";
import { ReportViewProps, } from "../../common/base";
import {
    末尾链接, 落款单位地址,
} from "../../common/rarelyVary";
import {
    依据检测仪器,
    制动距离,
    报告设备详情, 评估综述结论, 运行质量记录表, 限速器动作速度校验, 首页设备概况,
} from "./repView";
import {useRepMenuDirItems, } from "../../hook/useMainRepUrlOr";
import {setupItemAreaRoute} from "./orcIspConfig";
import queryString from "query-string";
import {FormatOriginal, 特殊项目编码} from "./FormatOriginal";
import RoutingContext from "../../../routing/RoutingContext";
import {useContext} from "react";
import {useLikeSafeEvalOfficial} from "../hook/useLikeSafeEvalOfficial";
import {ReportFirstPageHeadSimpNQR, 注意事项评估} from "../rarelyVary";
import {UnqualifiedIspTableEvalSplit} from "../general";
import {useItemsMapEval} from "../config";
import {useCalcEvalTotalScore} from "../hook/useCalcEvalTotalScore";
import {floatInterception} from "../../../common/tool";

export const ReportView: React.FunctionComponent<ReportViewProps> = ({
repId,  source: orc,  verId,rep,
}) => {
    const qs= queryString.parse(window.location.search);
    const formatOriginal =qs && !!qs.original;      //改成  格式化版原始记录
    const { history } = useContext(RoutingContext);
    const Component=formatOriginal? FormatOriginal : OfficialReport;
    return (<>
        <Component  source={orc} verId={verId} repId={repId} rep={rep}/>
        <div css={{margin: '0.5rem', "@media print": {display: 'none'} }}>
            <Button intent="danger" variant="outline"
                  onPress={async () => {
                      qs.original =formatOriginal? '' : '1';
                      history.location.search = queryString.stringify(qs);
                      const toUrl= history.createHref(history.location);
                      history.push(toUrl);
                  }}>{formatOriginal? '正式报告':'格式化版原始记录'}
            </Button>
        </div>
    </>);
}
//页面哈希路由方式
const JumpTags=[{name:'设备概况',ha:'Survey'},{name:'表1 不符合安全技术规范要求必须整改的项目',ha:'ReCheckA'},
                 {name:'3.1A 曳引系统U1（0.17）',ha:'3.1'},{name:'10.1 重量平衡系统U5',ha:'10.1'},{name:'附录A 电梯限速器动作速度校验',ha:'Limiter'}];
const 检验结果替换 =((orc: { [x: string]: any; }) => {
    let out={... orc};       //特殊测量数据需规整计算后替代原本orc的对应字段。
    return out;
});
/**直板手机目前超过6英寸，竖屏的(2024年见的)1.5K 2K分辨率的宽度有411px情形下的报告导航情况看似可以接受。横屏后2个半边效果比360px宽的手机好多了。
 * 本模板异常？： 原始记录和报告不符合常规一一对应，有些自拆分项目没有体现到报告的项目行当中。
 * */
const OfficialReport: React.FunctionComponent<ReportViewProps> = ({
    repId,   source: orc,  verId,rep,
}) => {
    const qs= queryString.parse(window.location.search);
    const printing =qs && !!qs.print;
    const theme= useTheme();
    const [rootMenu]=useRepMenuDirItems(JumpTags, [],`/reportView/SAFT-EL/ver/${verId}/${repId}`);
    const impressionismAs =React.useMemo(() => {
        return setupItemAreaRoute({verId, repId:repId!, theme});
    }, [verId, repId, theme]);
    // const itRes =React.useMemo(()=>检验结果替换(orc), [orc]);
    const {renderIspContent} =useLikeSafeEvalOfficial({itRes:orc,ItemArs:impressionismAs?.Item, model:'SAFT-EL',ver:verId, repId:repId!});
    const [mapNoTag]=useItemsMapEval({ ItemArs:impressionismAs?.Item, noCB:特殊项目编码 });
    const evalTotalScore=floatInterception(useCalcEvalTotalScore({itRes:orc, ItemArs:impressionismAs?.Item}),2);
   return (
    <React.Fragment>
      {rootMenu}
      <div css={{
            "@media not print": {
              marginTop:'1rem',
              marginBottom: '1rem'
            }
          }}
      >
       <div css={{
           "@media print": {
               height:'100vh',       //一张纸的高度！同时配合 pageBreakAfter: 'always', 来约束特定纸张大小；
               // overflowY: 'hidden'     //【注意局限性啊】一页内容，纸张规格；假如实际的数据超出自然不打印的！ 不加上打印重叠的；
           }
       }}>
        { ReportFirstPageHeadSimpNQR({theme,rep, mbbm:'FJB/TM-1007-1-0-2022'}) }
           <div css={{
               "@media print": {
                   display: 'flex',
                   flexDirection: 'column',
                   justifyContent: 'space-between',
                   height: 'calc(100vh - 125px)',     //剪掉上面头部的高度：适应特定纸张的布局: 125是可变的
               }
           }}>
               <Text variant="h3" css={{
                   textAlign:'center',
                   "@media print": {
                       fontSize: theme.fontSizes[5],
                       marginTop: '1.5rem',
                   },
               }}>
                 电梯安全性能技术评估报告
               </Text>
               { 首页设备概况( {theme, orc, rep} ) }
               <div css={{
                   textAlign:'center',
                   "@media print": {
                       pageBreakAfter:'always',
                       pageBreakInside:'avoid'
                   }
               }}>
                 {落款单位地址}
               </div>
           </div>
       </div>
          <RouterLink  href={`/report/SAFT-EL/ver/${verId}/${repId}/FrontCover`}>
            {注意事项评估({comply:'适用于曳引式电梯安全性能技术评估', rep,
                  tline: '本次电梯安全性能技术评估，仅针对本台电梯的现状提出可能存在的相关风险和安全隐患，仅对评估时的设备状况负责。' }) }
          </RouterLink>
          <DirectLink  href={`/report/SAFT-EL/ver/${verId}/${repId}/Instrument`}>
              <div css={{
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  "@media print": {
                      pageBreakBefore: 'always',
                  },
              }}>
              <Text variant="h4">一、设备概况</Text>
              </div>
          </DirectLink>
         {报告设备详情({orc, repId:repId!, verId,rep})}
         {依据检测仪器({orc, repId:repId!, verId,rep})}
         {评估综述结论({orc, repId:repId!, verId,rep, evalTotalScore})}
        <UnqualifiedIspTableEvalSplit rep={rep} orc={orc} mapNoTag={mapNoTag} printing={printing}/>
          <Text variant="h4" css={{
              "@media print": {
                  marginTop: '1rem',
              },
          }}>五、评估项目表</Text>
          <Table fixed={ ["3%","7.5%","10%","9%","%","7%","4.4%","5.5%","5%","5%","4.5%"] }
                 css={ {borderCollapse: 'collapse',marginTop: '0rem'} }   tight  miniw={800}>
              <TableHead>
                  <DirectLink  href={`/report/SAFT-EL/ver/${verId}/${repId}/ALL`}>
                      <TableRow>
                          <CCell>序号</CCell>
                          <CCell colSpan={2}>项目</CCell>
                          <CCell>项目编号</CCell>
                          <CCell>评估内容与要求</CCell>
                          <CCell>检测结果</CCell>
                          <CCell>严重程度</CCell>
                          <CCell>风险频率</CCell>
                          <CCell>风险类别</CCell>
                          <CCell>权重</CCell>
                          <CCell>得分</CCell>
                      </TableRow>
                  </DirectLink>
              </TableHead>
              <TableBody>
                  {renderIspContent}
              </TableBody>
          </Table>
          <Table fixed={ ["13%","60%","%"]  }   css={ {borderCollapse: 'collapse' } }  tight  miniw={800}>
              <TableBody>
                  <TableRow>
                      <CCell>总得分</CCell>
                      <CCell colSpan={2}>{ evalTotalScore }</CCell>
                  </TableRow>
              </TableBody>
          </Table>
          <Text id={'Limiter'} variant="h4" css={{marginTop: '1rem',
          }}>附录A 电梯限速器动作速度校验</Text>
          <Table fixed={ ["20%","8%","15%","8%","%","8%","12%","8%"] }  css={ {borderCollapse: 'collapse' } }  tight miniw={800}>
              {限速器动作速度校验({orc, repId:repId!, verId, rep})}
              {限速器动作速度校验({orc, repId:repId!, verId, rep, usecj:2})}
          </Table>
          {制动距离({orc, repId:repId!, verId, rep})}
          {运行质量记录表({orc, repId:repId!, verId, rep})}
      </div>

      {末尾链接({template:'SAFT-EL',verId, repId: repId||''})}
    </React.Fragment>
  );
}
